<?php

namespace app\controller\wmapi\partner;

use app\model\WaMembersAddress;
use Illuminate\Support\Facades;
use Illuminate\Support\Facades\Validator;
use plugin\admin\app\common\Util;
use plugin\admin\app\model\Admin;
use support\Request;
use app\model\WaAdmins;
use app\model\WaRoles;
use app\model\WaMembers;
use app\model\WaRules;
use app\model\WaDepartment;
use app\model\WaAdminRoles;
use Illuminate\Support\Facades\DB;
use Tymon\JWTAuth\Facades\JWTAuth;
use Illuminate\Support\Facades\Cache;
use Tinywan\Validate\Validate;
use app\controller\wmapi\IndexController;
use function GuzzleHttp\json_decode;

class MemberController extends Validate
{
    /**
     * 客户管理 -列表-分页
     * @param Request $request
     * @return mixed
     */
    public function memberList(Request $request)
    {
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        $pageNum = $param['pageNum'] ? $param['pageNum'] : 10;
        $fields = ['*'];
        $condition = [];
        $between = [];
        if ($param['name']) {
            $condition [] = ['name', 'like', '%' . $param['name'] . '%'];
        }

        if ($param['phone']) {
            $condition [] = ['phone', 'like', '%' . $param['phone'] . '%'];
        }

        if ($param['email']) {
            $condition [] = ['email', 'like', '%' . $param['email'] . '%'];
        }

        if ($param['country']) {
            $condition [] = ['country', 'like', '%' . $param['country'] . '%'];
            $condition [] = ['area', 'like', '%' . $param['country'] . '%'];
        }

        if ($param['start_time'] && $param['end_time']) {
            $between [] = [$param['start_time'], $param['end_time']];
        }

        $next_epartment_members = IndexController::nextDepartmentMembers($adminId);
        $whereIn = $next_epartment_members;
        if ($adminId->id == 39) {
            $whereIn = [];
        }

        $page = $param['page'] ? $param['page'] : 1;
        $rule = WaMembers::list($page, $pageNum, $whereIn, $fields, $condition, $between);

        return IndexController::successed($rule, '客户列表');
    }

    /**
     * 客户管理 -列表-不分页
     * @param Request $request
     * @return mixed
     */
    public function memberAll(Request $request)
    {
//        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        $fields = ['*'];
        $condition = [];
        if ($param['name']) {
            $condition [] = ['name', 'like', '%' . $param['name'] . '%']; // 产品品牌名称
        }
        $next_epartment_members = IndexController::nextDepartmentMembers($adminId);
        $whereIn = $next_epartment_members;
//        $condition [] = ['created_id', '=', intval($adminId->id)]; // 当前管理员对应的客户
        $rule = WaMembers::all($fields, $condition, $whereIn);
        return IndexController::successed($rule, '客户列表');
    }

    /**
     * 客户-创建
     * @param Request $request
     * @return \support\Response
     */
    public function memberCreate(Request $request)
    {
//        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        /**
         * 验证规则
         */
        $rule = [
            'name' => 'require|max:50',
            'maintainer_admin_id' => 'require',
            'phone' => 'require',
            'type' => 'require',
        ];
        $data = [
            'name' => $param['name'], // 客户名字/企业名称
            'country' => $param['country'],
//            'province' => $param['province'],
//            'city' => $param['city'],
            'area' => $param['area'],
//            'area_code' => $param['area_code'],
            'address' => $param['address'],
            'phone' => $param['phone'],
            'email' => $param['email'],
            'passport_number' => $param['passport_number'],// 护照号码
            'maintainer_admin_id' => $adminId->id,// 维护人(admin_id)
            'business_license_number' => $param['business_license_number'],// 营业执照号
            'tax_registration_number' => $param['tax_registration_number'],// 税务登记号
            'remark' => $param['remark'],// 备注
            'type' => $param['type'],// 1个人 2 企业
            'linkman' => $param['linkman'],
            'created_at' => dateTime(),
            'created_id' => $adminId->id, // 创建人
            'status' => 0,
            'term_id' => $adminId->department_id,
            'postal_code' => $param['postal_code'],// 邮编
//            'member_reference_id' => $param['member_reference_id'],// 推荐人id
            'attachment' => json_encode($param['attachment'])// 附件
        ];
        if ($param['channel_id']) {
            $data['channel_id'] = $param['channel_id'];
        }

        if ($param['member_reference_id']) {
            $data['member_reference_id'] = $param['member_reference_id'];// 推荐人id
        }
//        $validate = \Tinywan\Validate\Facade\Validate::rule($rule);
//        if (!$validate->check($param)) {
//            return IndexController::errored($validate->getError());
//        } else {
        $where = ['phone' => $param['phone']];
        $find = WaMembers::find($where);
        $find = json_decode($find);
        if ($find) {
            if (property_exists($find, 'id')) {
                return IndexController::errored('', '客户创建失败,客户电话已存在');
            }
        }


        \support\Db::beginTransaction();
        try {
            $res = WaMembers::created($data);
            $member_address_data = [
                'country' => $param['country'],
                'area' => $param['area'],
                'created_at' => dateTime(),
            ];
            $members_address = WaMembersAddress::find(['country' => $param['country'],
                'area' => $param['area']]);
            $members_address = json_decode($members_address);
            if (!$members_address) {
                $res = WaMembersAddress::created($member_address_data);
            }

            \support\Db::commit();
            return IndexController::successed($res, '客户创建成功');
        } catch (\Throwable $exception) {
            IndexController::logError('memberCreate', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '客户创建失败');
        }
//        }

    }

    /**
     * 客户-更新
     * @param Request $request
     * @return \support\Response
     */
    public function memberEdit(Request $request)
    {
//        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        /**
         * 验证规则
         */
        $rule = [
            'name' => 'require|max:50',
//            'maintainer_admin_id' => 'require',
            'phone' => 'require',
            'type' => 'require',
            'member_id' => 'require',
        ];

        $data = [
            'name' => $param['name'], // 客户名字/企业名称
            'country' => $param['country'],
//            'province' => $param['province'],
//            'city' => $param['city'],
            'area' => $param['area'],
//            'area_code' => $param['area_code'],
            'address' => $param['address'],
            'phone' => $param['phone'],
            'email' => $param['email'],
            'passport_number' => $param['passport_number'],// 护照号码
//            'maintainer_admin_id' => $param['maintainer_admin_id'],// 维护人(admin_id)
            'business_license_number' => $param['business_license_number'],// 营业执照号
            'tax_registration_number' => $param['tax_registration_number'],// 税务登记号
            'type' => $param['type'],// 1个人 2 企业
            'linkman' => $param['linkman'],
            'remark' => $param['remark'],// 备注
            'updated_at' => dateTime(),
            'term_id' => $adminId->department_id,
            'postal_code' => $param['postal_code'],// 邮编
//            'member_reference_id' => $param['member_reference_id'],// 推荐人id
            'attachment' => json_encode($param['attachment'])// 附件
        ];
        if ($param['member_reference_id']) {
            $data['member_reference_id'] = $param['member_reference_id'];// 推荐人id
        }

        if (array_key_exists('maintainer_admin_id', $param)) {
            if ($param['maintainer_admin_id']) {
                $data['maintainer_admin_id'] = json_encode($param['maintainer_admin_id']);// 维护人
            }
        }

        if (array_key_exists('maintainer_admin_ids', $param)) {
            if ($param['maintainer_admin_ids']) {
                $data['maintainer_admin_ids'] = json_encode($param['maintainer_admin_ids']);// 维护人回显参数（包括部门层级用于下拉赛选）
            }
        }

        if ($param['status'] || $param['status'] == 0) {
            $data['status'] = $param['status']; // 0默认  1正常 2 禁用 4 删除
        }
        if ($param['channel_id']) {
            $data['channel_id'] = $param['channel_id'];
        }


//        $validate = \Tinywan\Validate\Facade\Validate::rule($rule);
//        if (!$validate->check($param)) {
//            return IndexController::errored($validate->getError());
//        } else {
        $where = [];
        $where [] = ['id', '!=', $param['member_id']];
        $where [] = ['phone', '=', $param['phone']];
        $find = WaMembers::find($where);
        $find = json_decode($find);
        if ($find) {
            return IndexController::errored($find.$param['member_id'].$param['phone'], '客户更新失败,手机号已存在');
        }

        $condition = [];
        $condition [] = ['id', '=', intval($param['member_id'])];
        \support\Db::beginTransaction();
        try {
            $res = WaMembers::updated($condition, $data);

            $member_address_data = [
                'country' => $param['country'],
                'area' => $param['area'],
                'created_at' => dateTime(),
            ];
            $members_address = WaMembersAddress::find(['country' => $param['country'],
                'area' => $param['area']]);
            $members_address = json_decode($members_address);
            if (!$members_address) {
                $res = WaMembersAddress::created($member_address_data);
            }


            \support\Db::commit();
            return IndexController::successed($res, '客户更新成功');
        } catch (\Throwable $exception) {
            IndexController::logError('memberEdit', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '客户更新失败');
        }
//        }
    }

    /**
     * 客户-删除
     * @param Request $request
     * @return \support\Response
     */
    public function memberDel(Request $request)
    {
//        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        $condition = [];
        $condition [] = ['id', '=', $param['member_id']];

        $data = [
            'status' => 4,
            'updated_at' => dateTime(),
        ];
        \support\Db::beginTransaction();
        try {
            $res = WaMembers::updated($condition, $data);
            \support\Db::commit();
            return IndexController::successed($res, '客户-删除成功');
        } catch (\Throwable $exception) {
            IndexController::logError('memberDel', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '客户-删除失败');
        }
    }

    /**
     * 管理员-详情
     * @param Request $request
     * @return \support\Response
     */
    public function memberDetail(Request $request)
    {
//        process($request);
        $param = $request->all();
        $condition = [];
        $condition [] = ['id', '=', $param['member_id']];
        $rule = WaMembers::find($condition);
//        $rule = json_decode($rule);
//        $rule->role_id = json_decode($rule->role_id);
//        $rule = json_encode($rule);
        return IndexController::successed($rule, '客户信息');
    }

    /**
     * 维护人
     * @param Request $request
     * 需求:3.维护人：（下级->没有则默认选自己）
     * 同部门主管为上级，下级只能默认选自己
     */
    public function maintainer(Request $request)
    {
//        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        // 是否部门负责人 0不是 1是
        if ($adminId->is_principal == 1) {
            $res = WaAdmins::allId(['id', 'username', 'nickname'], ['department_id' => $adminId->department_id]);
//            $res = json_decode($res);

        } else {
            $res = WaAdmins::allId(['id', 'username', 'nickname'], ['id' => $adminId->id]);
        }

        return IndexController::successed($res, '');
    }

}